package com.zhilianbao.leyaogo.ui.fragment.me;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.recyclerview.swipe.SwipeMenu;
import com.bql.recyclerview.swipe.SwipeMenuAdapter;
import com.bql.recyclerview.swipe.SwipeMenuCreator;
import com.bql.recyclerview.swipe.SwipeMenuItem;
import com.bql.roundview.RoundTextView;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.listener.OnAddToCartClickListener;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.me.MyCollectionResponse;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.goodscategory.GoodsActivity;
import com.zhilianbao.leyaogo.ui.adapter.me.MyCollectionAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.SwipeRefreshAndLoadFragment;
import com.zhilianbao.leyaogo.ui.fragment.shoppingcart.ShoppingCartFragment;
import com.zhilianbao.leyaogo.utils.GoodsSpecPopUtils;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.ShopNumUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.decoration.ListLineDecoration;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liu on 2016/10/29.
 * 我的收藏
 */
public class MyCollectionFragment extends SwipeRefreshAndLoadFragment<MyCollectionResponse> implements OnAddToCartClickListener<MyCollectionResponse> {
    MyCollectionAdapter mMyCollectionAdapter;
    @BindView(R.id.iv_add_to_cart)
    ImageView ivAddToCart;
    @BindView(R.id.rl_collection_container)
    MyRelativeLayout mRlCollectionContainer;
    @BindView(R.id.iv_cart_num)
    RoundTextView mIvCartNum;
    @BindView(R.id.rl_add_to_cart)
    RelativeLayout mRlAddToCart;
    private CommonDialog mDelDialog;//确定是否删除弹框
    private int mGoodsSkuId;

    public static MyCollectionFragment getInstance() {
        MyCollectionFragment fragment = new MyCollectionFragment();
        return fragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("shopping_cart_num", LeYaoGoApplication.SHOPPING_CART_NUM);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null)
            ShopNumUtils.show(mIvCartNum, savedInstanceState.getInt("shopping_cart_num"));
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        //进入商品详情
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.BUNDLE_GOODS_ID, (int) mList.get(position).getGoodsId());
        int goodsSkuId = mList.get(position).getGoodsSkuId();
        bundle.putInt(IntentConfig.BUNDLE_GOODS_SKU_ID, goodsSkuId);
        Utils.startActivity(mActivity, GoodsActivity.class, bundle);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_my_collection;
    }

    @Override
    public SwipeMenuAdapter getAdapter() {
        return mMyCollectionAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return new ListLineDecoration();
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }

    @Override
    public SwipeMenuCreator getSwipeMenuCreator() {
        return new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                SwipeMenuItem modifyItem = new SwipeMenuItem(mActivity)
                        .setBackgroundColor(getResources().getColor(R.color.color_f91c4c))
                        .setText(R.string.modify_delete)
                        .setTextColor(Color.WHITE)
                        .setWidth(getResources().getDimensionPixelSize(R.dimen.size70));
                swipeRightMenu.addMenuItem(modifyItem);
            }
        };
    }

    @Override
    public void onLeftSwipeMenuClick(int adapterPosition, int menuPosition) {

    }

    @Override
    public void onRightSwipeMenuClick(int adapterPosition, int menuPosition) {
        showDelDialog(adapterPosition);
    }

    /**
     * 删除提示框
     *
     * @param adapterPosition adapter index
     */
    private void showDelDialog(final int adapterPosition) {
        if (mDelDialog == null) {
            mDelDialog = CommonDialog.createTwoButton(getString(R.string.confirm), getString(R.string.cancel), getString(R.string.sure_cancel_collection_goods));
        }
        mDelDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                delCollectionGood(adapterPosition);
                mDelDialog.dismiss();
            }

            @Override
            public void right() {
                mDelDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mDelDialog.show(getFragmentManager(), "delete");
    }

    /**
     * 取消商品收藏
     *
     * @param pos
     */
    private void delCollectionGood(int pos) {
        MyCollectionResponse myCollectionResponse = mList.get(pos);
        AccountApi.setMyCollectionGoods(mActivity, 0, myCollectionResponse.getUserId(), myCollectionResponse.getSupplierId(), myCollectionResponse.getEnshrineType(),
                myCollectionResponse.getShopId(), myCollectionResponse.getGoodsId(), myCollectionResponse.getGoodsSkuId(), myCollectionResponse.getSetSign(),
                myCollectionResponse.getComments(), new DialogCallback<MyCollectionResponse>(mActivity) {

                    @Override
                    public void onSuccess(MyCollectionResponse myCollectionResponse, Call call, Response response) {
                        XToastUtils.showShortToast("取消商品收藏成功");
                        mList.remove(pos);
                        mMyCollectionAdapter.notifyItemRemoved(pos);
                        mMyCollectionAdapter.notifyItemRangeChanged(pos, mList.size());
                        if (mList.size() == 0) {
                            loadDataList(1, false);
                        }
                    }
                });
    }

    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        mCurPage = curPage;
        long supplierId = Utils.getSupplierId();
        int enshrineType = 1;//收藏类型 1商品 2店铺
        AccountApi.getMyCollectionGoodsList(mActivity, Utils.getUserLoginInfo().getUserId(), supplierId, enshrineType, curPage, 10, new RefreshAndLoadCallback<List<MyCollectionResponse>>(isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                TextView tv = (TextView) v;
                if (tv.getText().toString().trim().equals(emptyBtnText())) {
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SWITCH_TO_HOME));
                    mActivity.finish();
                } else {
                    loadDataList(1, false);
                }
            }

            @Override
            public void onResultSuccess(List<MyCollectionResponse> myCollectionResponses, @Nullable Response response, LoadingViewCallback callback) {
                init(myCollectionResponses);
                handleRefreshAndLoadListData(mCurPage, callback, myCollectionResponses);
            }

            @Override
            public Drawable emptyDrawable() {
                return getResources().getDrawable(R.drawable.img_collection_is_empty);
            }

            @Override
            public String emptyContent() {
                return getString(R.string.empty_collection);
            }

            @Override
            public boolean showEmptyButton() {
                return true;
            }

            @Override
            public String emptyBtnText() {
                return getString(R.string.empty_go);
            }
        });
    }

    private void init(List<MyCollectionResponse> myCollectionResponses) {
        if (myCollectionResponses.size() != 0) {
            mRlAddToCart.setVisibility(View.VISIBLE);
        } else {
            mRlAddToCart.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.my_collection_title));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mMyCollectionAdapter = new MyCollectionAdapter(mActivity, mList);
        mMyCollectionAdapter.setOnAddCartClickListener(this);
        ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
    }

    @OnClick(R.id.iv_add_to_cart)
    public void onClick() {
        start(ShoppingCartFragment.newInstance(true));
    }

    @Override
    public void onAddToCartClick(MyCollectionResponse myCollectionResponse, ImageView imageView) {
        if (Utils.isShowSpePop(myCollectionResponse.getGoodsType(), myCollectionResponse.getGoodsSkuId())) {//弹属性选择框
            showSkuPop(imageView, myCollectionResponse);
        } else {
            mGoodsSkuId = myCollectionResponse.getGoodsSkuId();
            addToShoppingCart(myCollectionResponse, imageView);
        }

    }

    private void addToShoppingCart(MyCollectionResponse myCollectionResponse, ImageView imageView) {
        ShoppingCartApi.setShoppingCart(mActivity, myCollectionResponse.getUserId(), myCollectionResponse.getGoodsId(), myCollectionResponse.getSupplierId(), myCollectionResponse.getShopId(), mGoodsSkuId, 1, 0, new DialogCallback<GoodsStock>(mActivity) {
            @Override
            public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                ShopAnimationUtils.addToShoppingCart(mActivity, 0, imageView, ivAddToCart, mRlCollectionContainer, true, () -> {
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                });
            }
        });
    }

    //显示是sku商品的规格选择提示框
    private void showSkuPop(ImageView imageView, MyCollectionResponse myCollectionResponse) {

        Utils.showSpecPop(mActivity, getView(), 1, myCollectionResponse.getGoodsPic(), myCollectionResponse.getGoodsSkuId(), myCollectionResponse.getSelectedSkuId(), myCollectionResponse.getSku(), myCollectionResponse.getSkuMap(), new GoodsSpecPopUtils.OnPopClickListener() {

            @Override
            public void onAddToCart(View v, int goodsSkuId) {
                mGoodsSkuId = goodsSkuId;
                addToShoppingCart(myCollectionResponse, imageView);
            }

            @Override
            public void onSpecSelect(SkuEntity skuEntity) {
                myCollectionResponse.setSelectedSkuId(skuEntity.getGoodsSkuId());
            }

        });

    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_SET_SHOPPINGCART_NUM://从我的收藏进入商品详情,购物车数据变化时通知收藏改变数据
            case LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART://添加购物车成功刷新购物车数量
            case LeEventCode.MSG_CODE_SET_SHOPPINGCART_SUCS://购物车数量改变
                ShopNumUtils.show(mIvCartNum, LeYaoGoApplication.SHOPPING_CART_NUM);
                break;
            case LeEventCode.MSG_CODE_SET_COLLECTION_SUCCESS://从我的收藏进入商品详情,取消收藏或添加收藏通知收藏改变数据
                loadDataList(1, false);
                break;
            case LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY://从收藏进入详情,进入购物车,点击去逛逛,finish掉优惠券页面
                mActivity.finish();
                break;
        }
    }
}
